package com.powerbosframework.jdbc.id;


import java.sql.SQLException;
import java.util.UUID;

import com.powerbosframework.jdbc.core.JdbcSessionFactory;
import com.powerbosframework.jdbc.core.JdbcTmplt;
import com.powerbosframework.jdbc.core.QueryTmplt;
import com.powerbosframework.log.LogFactory;
import com.powerbosframework.log.Logger;
import com.powerbosframework.jdbc.id.Identifier;


/**
 * 主键标识符生成器
 * @author youfu.wang
 * @version 1.0
 */
public class IdentifierGenerator implements Identifier{
	private Logger log=LogFactory.getInstance();
	private JdbcSessionFactory jdbcSessionFactory;

	public IdentifierGenerator(){
		
	}
	
	public IdentifierGenerator(JdbcSessionFactory jdbcSessionFactory){
		this.jdbcSessionFactory = jdbcSessionFactory;
	}
	/**
	 * 得到最大行数
	 * 
	 * @param sql
	 * @return
	 * @throws SQLException
	 */
	public int getROWNUM(String sql) throws SQLException {
		int rownum = 0;
		sql = "select count(*) from (" + sql + ")";
		JdbcTmplt jdbcTmplt=this.jdbcSessionFactory.getJdbcTmplt();	
		QueryTmplt queryTmplt = jdbcTmplt.createQueryTmplt();
		Object[] obj=queryTmplt.queryForArray(sql);		
		if(obj!=null){
			String value=String.valueOf(obj[0]);
			if(value!=null&&!"".equals(value)&&!"null".equals(value)){
				rownum=Integer.parseInt(value);
			}
		}		
		return rownum;
	}
	/**
	 * 得到全局标识符
	 * @param table
	 * @param primary
	 * @return
	 * @throws SQLException
	 */
	public Long getID(String table,String primary) throws SQLException{
		Long id=0L;
		String sql="select max("+primary+") from "+table;
		JdbcTmplt jdbcTmplt=this.jdbcSessionFactory.getJdbcTmplt();	
		QueryTmplt queryTmplt = jdbcTmplt.createQueryTmplt();
		Object[] obj=queryTmplt.queryForArray(sql);		
		if(obj!=null){
			String value=String.valueOf(obj[0]);
			if(value!=null&&!"".equals(value)&&!"null".equals(value)){
				id=Long.parseLong(value);
			}		
		}		
		return id=id+1L;
	}
	/**
	 * 得到全局标识符
	 * @param table
	 * @param primary
	 * @param prefix
	 * @param length
	 * @return
	 * @throws SQLException
	 */
	public Long getID(String table,String primary,long prefix,long length) throws SQLException{
		Long id=0L;
		String sql="select max("+primary+") from "+table;
		JdbcTmplt jdbcTmplt=this.jdbcSessionFactory.getJdbcTmplt();	
		QueryTmplt queryTmplt = jdbcTmplt.createQueryTmplt();
		Object[] obj=queryTmplt.queryForArray(sql);		
		if(obj!=null){
			String value=String.valueOf(obj[0]);
			if(value!=null&&!"".equals(value)&&!"null".equals(value)){
				id=Long.parseLong(value);
			}			
		}	
		if(id==0L){							
			for(int i=0;i<length;i++){
				id=prefix*10;
				prefix=prefix*10;				
				if(String.valueOf(id).length()>=length){
					break;
				}
			}
		}			
		return id=id+1L;
	}
	/**
	 * 得到全局标识符
	 * @return
	 */
	public Object getUUID(){
		UUID uuid = UUID.randomUUID(); 
		return uuid.toString();
	}
}
